package exception;

import java.util.NoSuchElementException;

public class DynamicFields {
	private Object[][] fields;
	
	private DynamicFields(int size){
		fields = new Object[size][2];
		for(int i = 0; i < size; i++)
			fields[i] = new Object[]{null, null};
	}
	
	public String toString(){
		StringBuilder sb = new StringBuilder();
		for(Object[] obj : fields){
			//System.out.println(obj);
			sb.append(obj[0]);
			sb.append(":");
			sb.append(obj[1]);
			sb.append("\n");
		}
		return sb.toString();
	}
	
	private int hasField(String id){
		for(int i = 0; i < fields.length; i ++)
			if(id.equals(fields[i][0]))
				return i;
		return -1;
	}
	
	private int getFieldNumber(String id) throws NoSuchFieldException{
		int fieldNumber = hasField(id);
		if(fieldNumber == -1)
			throw new NoSuchFieldException();
		return fieldNumber;
	}
	
	private int makeField(String id){
		for(int i = 0; i < fields.length; i++){
			if(fields[i][0] == null){
				fields[i][0] = id;
				return i;
			}
		}
		Object[][] temp = new Object[fields.length][2];
		for(int i = 0; i < fields.length; i++)
			temp[i] = fields[i];
		fields = new Object[fields.length + 1][2];
		for(int i = 0; i < temp.length; i++)
			fields[i] = temp[i];
		return makeField(id);
	}
	
	private Object getField(String id) throws NoSuchFieldException{
		return fields[getFieldNumber(id)][1];
	}
	
	private Object setField(String id, Object value) throws DynamicFieldException{
		if(value == null){
			//throw new DynamicFieldException();
			DynamicFieldException dfe = new DynamicFieldException();
			dfe.initCause(new NullPointerException());
			throw dfe;
		}
		int index = hasField(id);
		if(index == -1)
			index = makeField(id);
		Object result = null;
		try {
			result = getField(id);// old Field
		} catch (NoSuchFieldException e) {
			throw new RuntimeException(e);
		}
		fields[index][1] = value;
		return result;
	}
	
	
	public static void main(String[] args){
		DynamicFields df = new DynamicFields(3);
		System.out.println(df);
		try{
			df.setField("A", "A Value");
			df.setField("B", "B Value");
			df.setField("C", "C Value");
			
			df.setField("D", "D Value");
			df.setField("C", "C New Value");
			System.out.println(df);
			System.out.println(df.getField("A"));
			df.setField("Null", null);
		} catch (DynamicFieldException e){
			e.printStackTrace(System.err);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		
	}
}

class DynamicFieldException extends Exception{
	
}
